package com.candy.candycommon.config;

import com.gitee.candy.constant.ConstantUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * @author suYanLong
 * @date 2022年10月21日 11:06
 */
@Slf4j
@Configuration
public class FeignOkHttpClientConfig {

    @Bean
    public OkHttpClient.Builder okHttpClientBuilder() {
//        return new OkHttpClient.Builder().addInterceptor(new FeignOkHttpClientResponseInterceptor());
        return new OkHttpClient.Builder();
    }

    /**
     * okHttp响应拦截器
     */
    public static class FeignOkHttpClientResponseInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {

            Request originalRequest = chain.request().newBuilder().addHeader(ConstantUtils.TRACE_ID, MDC.get(ConstantUtils.TRACE_ID)).build();
            log.info(originalRequest.header(ConstantUtils.TRACE_ID));
            Response response = chain.proceed(originalRequest);

            MediaType mediaType = response.body().contentType();
            String content = response.body().string();

            //解析content，做你想做的事情！！
            log.info(" 返回调用：{} ", content);
            //生成新的response返回，网络请求的response如果取出之后，直接返回将会抛出异常
            return response.newBuilder()
                    .body(ResponseBody.create(mediaType, content))
                    .build();
        }

    }

}
